$(document).ready(function() {	
	$("#frmAdd").validate({
		errorClass		: 'error',
		errorElement	: 'span',
		onfocusout		: false,
		onkeyup			: false,
		ignore			: "input[type='text']:hidden",
		rules: {							
			pname:{
				required			: true,
				minlength			: 2,
				validateFormat		: true
			},			
			plabel: {
				required			: true,
				minlength			: 2
			},
			ptag: {
				validateOpts		: true
			},
			pmsg_required: {
				required			: true
			}			
		},
		messages: {				
			pname:{
				required			: name_required,
				minlength			: name_minlength,
				validateFormat		: name_format
			},
			plabel: {
				required			: label_required,
				minlength			: label_minlength
			},
			ptag: {
				validateOpts		: table_opt_required
			},
			pmsg_required: {
				required			: msg_required
			}
		},
		errorPlacement: function(label, element) {
			var id = element.attr('id');	
			if(id == 'ptag') {
				label.insertAfter($('#tbOpts tfoot td button'));	
			} else {
				label.insertAfter($('#' + id));				
			}
		},
		submitHandler: function(form) {	
			var tag    = $('#ptag').val();						
			if(tag != 'text' && tag != 'textarea') {
				var opts = [];
				$('#tbOpts input[type="text"]').each(function(index){															  
					opts[index] = {value:index+1,label:$(this).val()};
				});
				$('#popts').val(JSON.stringify(opts));
			}
			form.submit();
		}
	});	
	$.validator.addMethod('validateFormat', function() {
		var name = $('#pname').val();
		return validateCode(name);
	});	
	$.validator.addMethod('validateOpts', function(){
		var result = true;
		var tag    = $('#ptag').val();
		
		if(tag != 'text' && tag != 'textarea') {
			$('#tbOpts input[type="text"]').each(function(){
				if($(this).val() == '') {
					result = false;						
				}
				if(result == false) return false;
			});
		}	
		return result;
	});
	/*
	$('#tbOpts a.remove').live('click', function() {
		var lenTr = $('#tbOpts tbody tr').length;
		if(lenTr == 1) {
			alert(table_opt_remove);
			return false;
		}		
		$(this).parents("tr").remove();		
	});			
	*/
});
changeTag = function(val,div) {	
	if(val != 'text' && val != 'textarea') {
		$('#' + div).show();
	}else {
		$('#' + div).hide();
	}
}
changeMsg = function(val,div) {
	if(val == 0) $('#' + div).hide();
	else $('#' + div).show();
}